package com.mo.manage;

import com.mo.mapper.TCluemapper;
import com.mo.mapper.TCustomermapper;
import com.mo.model.TClue;
import com.mo.model.TCustomer;
import com.mo.model.TUser;
import com.mo.query.CustomerQuery;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author mo
 * version
 */
@Component
public class CustomerManager {
    @Resource
    private TCustomermapper tCustomermapper;

    @Resource
    private TCluemapper tCluemapper;

    @Transactional(rollbackFor = Exception.class)
    public Boolean convertCustomer(CustomerQuery customerQuery){
        //1.验证该线索是否已经转过客户，转过就不能再转了
        TClue tClue = tCluemapper.selectByPrimaryKey(customerQuery.getClueId());
        if (tClue.getState() == -1){
            throw new RuntimeException("该线索已经转过客户，不能能再转了");
        }
        //2.向向客户表插入一条数据
        TCustomer tCustomer = new TCustomer();
        BeanUtils.copyProperties(customerQuery,tCustomer);
        TUser user = (TUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        tCustomer.setCreateTime(new Date());
        tCustomer.setCreateBy(user.getId());
        int insert=tCustomermapper.insertSelective(tCustomer);
        //3.把线索表的数据状态改为-1
        tClue.setState(-1);
        int update=tCluemapper.updateByPrimaryKeySelective(tClue);
        return insert>=1 && update >=1;
    }
}
